#!/usr/bin/env node

const http = require('http');
const fs = require('fs');
const {join} = require('path');

http.createServer((req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');//跨域策略的设置
    let url = new URL(req.url, `http://${req.headers.host}`);
    // console.log(url);
    if(url.pathname === '/api') {
        // console.log('api', req.url);
        api(url, res);
    } else {
        // console.log('file', req.url);
        file(req, res);
    }
    // 一个终端执行all-in-one.js
    // api请求curl http://localhost:3000/api\?width\=4\&height\=5
    // 文件请求curl http://localhost:3000/index.html
    // 文件请求curl http://localhost:3000/rectangle.js
    // res.end("ok");
}).listen(3000);

function api(url, res) {
    const width = Number(url.searchParams.get('width'));
    const height = Number(url.searchParams.get('height'));
    
    const rect = {
        area:width * height,
        perimeter: 2 * (width + height),
    };
    res.end(JSON.stringify(rect));
}

function file(req, res) {
    let fileName = req.url.slice(1);
    // console.log(fileName);
    // 找文件 www/index.html
    fileName = join(__dirname, fileName);
    console.log(fileName);
    //if fileName not exists res 404 not found
    if(!fs.existsSync(fileName)) {
        res.statusCode = 404;
        res.end(`${req.url} not found`);
        return;
    }
    // then res send file content
    res.end(fs.readFileSync(fileName, 'utf8'));

}


